// 圣经问答游戏 - 计分系统

class ScoringSystem {
    constructor() {
        // 基础分数配置
        this.basePoints = {
            explorer: 10,    // 探索者基础分
            adventurer: 15,  // 冒险家基础分
            hero: 20,        // 英雄基础分
            legend: 25       // 传奇基础分
        };

        // 时间奖励配置（秒）
        this.timeBonus = {
            excellent: { threshold: 5, multiplier: 2.0 },   // 5秒内答题，2倍奖励
            good: { threshold: 10, multiplier: 1.5 },       // 10秒内答题，1.5倍奖励
            normal: { threshold: 20, multiplier: 1.2 }      // 20秒内答题，1.2倍奖励
        };

        // 连击奖励配置
        this.streakBonus = {
            3: 1.2,   // 连续3题正确，1.2倍
            5: 1.5,   // 连续5题正确，1.5倍
            8: 1.8,   // 连续8题正确，1.8倍
            10: 2.0,  // 连续10题正确，2倍
            15: 2.5   // 连续15题正确，2.5倍
        };

        // 完成奖励
        this.completionBonus = {
            explorer: 50,
            adventurer: 100,
            hero: 200,
            legend: 300
        };

        // 准确率奖励
        this.accuracyBonus = {
            100: 300,  // 100%准确率
            90: 200,   // 90%以上
            80: 100,   // 80%以上
            70: 50     // 70%以上
        };

        this.reset();
    }

    // 重置计分系统
    reset() {
        this.currentScore = 0;
        this.currentStreak = 0;
        this.maxStreak = 0;
        this.totalQuestions = 0;
        this.correctAnswers = 0;
        this.startTime = Date.now();
        this.questionStartTime = Date.now();
        this.scoreHistory = [];
        this.difficulty = 'beginner';
    }

    // 设置游戏难度
    setDifficulty(difficulty) {
        this.difficulty = difficulty;
    }

    // 开始新题目
    startQuestion() {
        this.questionStartTime = Date.now();
    }

    // 计算单题得分
    calculateQuestionScore(isCorrect, answerTime = null) {
        if (!isCorrect) {
            this.currentStreak = 0;
            return 0;
        }

        // 基础分数
        let score = this.basePoints[this.difficulty];

        // 时间奖励
        const timeSpent = answerTime || (Date.now() - this.questionStartTime) / 1000;
        const timeMultiplier = this.getTimeMultiplier(timeSpent);
        score *= timeMultiplier;

        // 连击奖励
        this.currentStreak++;
        this.maxStreak = Math.max(this.maxStreak, this.currentStreak);
        const streakMultiplier = this.getStreakMultiplier(this.currentStreak);
        score *= streakMultiplier;

        // 四舍五入到整数
        score = Math.round(score);

        // 记录得分历史
        this.scoreHistory.push({
            questionNumber: this.totalQuestions + 1,
            baseScore: this.basePoints[this.difficulty],
            timeMultiplier,
            streakMultiplier,
            finalScore: score,
            timeSpent: Math.round(timeSpent * 10) / 10,
            streak: this.currentStreak
        });

        return score;
    }

    // 获取时间奖励倍数
    getTimeMultiplier(timeSpent) {
        if (timeSpent <= this.timeBonus.excellent.threshold) {
            return this.timeBonus.excellent.multiplier;
        } else if (timeSpent <= this.timeBonus.good.threshold) {
            return this.timeBonus.good.multiplier;
        } else if (timeSpent <= this.timeBonus.normal.threshold) {
            return this.timeBonus.normal.multiplier;
        }
        return 1.0;
    }

    // 获取连击奖励倍数
    getStreakMultiplier(streak) {
        // 找到适用的最高连击奖励
        let multiplier = 1.0;
        Object.entries(this.streakBonus).forEach(([threshold, bonus]) => {
            if (streak >= parseInt(threshold)) {
                multiplier = Math.max(multiplier, bonus);
            }
        });
        return multiplier;
    }

    // 提交答案并更新分数
    submitAnswer(isCorrect, answerTime = null) {
        this.totalQuestions++;
        
        if (isCorrect) {
            this.correctAnswers++;
            const questionScore = this.calculateQuestionScore(true, answerTime);
            this.currentScore += questionScore;
            return {
                correct: true,
                score: questionScore,
                totalScore: this.currentScore,
                streak: this.currentStreak,
                timeBonus: this.getTimeMultiplier(answerTime || (Date.now() - this.questionStartTime) / 1000),
                streakBonus: this.getStreakMultiplier(this.currentStreak)
            };
        } else {
            this.currentStreak = 0;
            return {
                correct: false,
                score: 0,
                totalScore: this.currentScore,
                streak: 0,
                timeBonus: 1.0,
                streakBonus: 1.0
            };
        }
    }

    // 计算最终分数（包含完成奖励和准确率奖励）
    calculateFinalScore() {
        let finalScore = this.currentScore;

        // 完成奖励
        if (this.totalQuestions > 0) {
            finalScore += this.completionBonus[this.difficulty] || 0;
        }

        // 准确率奖励
        const accuracy = this.getAccuracy();
        const accuracyBonusPoints = this.getAccuracyBonus(accuracy);
        finalScore += accuracyBonusPoints;

        return {
            baseScore: this.currentScore,
            completionBonus: this.completionBonus[this.difficulty] || 0,
            accuracyBonus: accuracyBonusPoints,
            finalScore: Math.round(finalScore)
        };
    }

    // 获取准确率奖励分数
    getAccuracyBonus(accuracy) {
        if (accuracy >= 100) return this.accuracyBonus[100];
        if (accuracy >= 90) return this.accuracyBonus[90];
        if (accuracy >= 80) return this.accuracyBonus[80];
        if (accuracy >= 70) return this.accuracyBonus[70];
        return 0;
    }

    // 获取当前准确率
    getAccuracy() {
        if (this.totalQuestions === 0) return 0;
        return Math.round((this.correctAnswers / this.totalQuestions) * 100);
    }

    // 获取游戏统计
    getGameStats() {
        const totalTime = Math.round((Date.now() - this.startTime) / 1000);
        const accuracy = this.getAccuracy();
        const finalScoreData = this.calculateFinalScore();

        return {
            totalQuestions: this.totalQuestions,
            correctAnswers: this.correctAnswers,
            accuracy,
            currentStreak: this.currentStreak,
            maxStreak: this.maxStreak,
            score: this.currentScore,
            finalScore: finalScoreData.finalScore,
            completionBonus: finalScoreData.completionBonus,
            accuracyBonus: finalScoreData.accuracyBonus,
            timeTaken: totalTime,
            difficulty: this.difficulty,
            averageTimePerQuestion: this.totalQuestions > 0 ? Math.round(totalTime / this.totalQuestions * 10) / 10 : 0
        };
    }

    // 获取详细的得分分析
    getScoreAnalysis() {
        const stats = this.getGameStats();
        
        return {
            ...stats,
            scoreBreakdown: {
                basePoints: this.scoreHistory.reduce((sum, item) => sum + item.baseScore, 0),
                timeBonus: this.scoreHistory.reduce((sum, item) => 
                    sum + (item.baseScore * (item.timeMultiplier - 1)), 0),
                streakBonus: this.scoreHistory.reduce((sum, item) => 
                    sum + (item.baseScore * item.timeMultiplier * (item.streakBonus - 1)), 0),
                completionBonus: stats.completionBonus,
                accuracyBonus: stats.accuracyBonus
            },
            questionDetails: this.scoreHistory,
            performance: this.getPerformanceRating(stats.accuracy, stats.maxStreak, stats.timeTaken)
        };
    }

    // 获取表现评级
    getPerformanceRating(accuracy, maxStreak, timeTaken) {
        let rating = 'bronze';
        let message = '继续努力！';

        if (accuracy >= 90 && maxStreak >= 10) {
            rating = 'diamond';
            message = '完美表现！你是真正的圣经学者！';
        } else if (accuracy >= 80 && maxStreak >= 8) {
            rating = 'gold';
            message = '优秀表现！你对圣经知识掌握得很好！';
        } else if (accuracy >= 70 && maxStreak >= 5) {
            rating = 'silver';
            message = '良好表现！继续学习会更棒！';
        } else if (accuracy >= 60 || maxStreak >= 3) {
            rating = 'bronze';
            message = '不错的开始！多练习会有进步！';
        }

        // 速度奖励评价
        const avgTime = timeTaken / Math.max(1, this.totalQuestions);
        if (avgTime <= 8) {
            message += ' 而且答题速度很快！';
        }

        return { rating, message };
    }

    // 获取分数等级
    getScoreGrade(score) {
        const grades = [
            { min: 1500, grade: 'S+', title: '圣经大师', color: '#ff6b6b' },
            { min: 1200, grade: 'S', title: '圣经专家', color: '#4ecdc4' },
            { min: 1000, grade: 'A+', title: '圣经学者', color: '#45b7d1' },
            { min: 800, grade: 'A', title: '知识渊博', color: '#96ceb4' },
            { min: 600, grade: 'B+', title: '学有所成', color: '#feca57' },
            { min: 400, grade: 'B', title: '初有成就', color: '#ff9ff3' },
            { min: 200, grade: 'C+', title: '努力学习', color: '#54a0ff' },
            { min: 100, grade: 'C', title: '刚刚起步', color: '#5f27cd' },
            { min: 0, grade: 'D', title: '继续加油', color: '#00d2d3' }
        ];

        return grades.find(g => score >= g.min) || grades[grades.length - 1];
    }

    // 比较两次游戏成绩
    compareWithBest(bestScore) {
        const currentStats = this.getGameStats();
        const improvement = {
            score: currentStats.finalScore - bestScore,
            isNewRecord: currentStats.finalScore > bestScore
        };

        let message = '';
        if (improvement.isNewRecord) {
            message = `🎉 新纪录！比最佳成绩高出 ${improvement.score} 分！`;
        } else if (improvement.score >= -50) {
            message = `😊 接近最佳成绩！只差 ${Math.abs(improvement.score)} 分！`;
        } else {
            message = `💪 继续努力！距离最佳成绩还有 ${Math.abs(improvement.score)} 分！`;
        }

        return { ...improvement, message };
    }

    // 生成分享文本
    generateShareText() {
        const stats = this.getGameStats();
        const grade = this.getScoreGrade(stats.finalScore);
        
        const difficultyNames = {
            explorer: '探索者',
            adventurer: '冒险家',
            hero: '英雄',
            legend: '传奇'
        };

        const shareTexts = [
            `我在圣经问答游戏中获得了 ${stats.finalScore} 分！难度：${difficultyNames[this.difficulty]}，正确率：${stats.accuracy}%，等级：${grade.grade} ${grade.title}！`,
            `圣经问答挑战完成！${difficultyNames[this.difficulty]}难度得分 ${stats.finalScore}，正确率 ${stats.accuracy}%，最高连击 ${stats.maxStreak} 题！`,
            `刚完成了一轮圣经问答！${grade.title}等级，${stats.finalScore}分，你能超过我吗？`
        ];

        return shareTexts[Math.floor(Math.random() * shareTexts.length)];
    }

    // 获取得分提示
    getScoreTips() {
        const tips = [
            '💡 快速答题可以获得时间奖励！',
            '🔥 连续答对题目会有连击奖励！',
            '🎯 提高准确率可以获得额外奖励！',
            '⭐ 完成游戏会有完成奖励！',
            '🏆 挑战更高难度可以获得更多基础分！'
        ];

        return tips[Math.floor(Math.random() * tips.length)];
    }
}

// 创建全局计分系统实例
window.scoringSystem = new ScoringSystem();